#include "FileManager.h"
#include <header.h>

void computemd5(int fileDescriptor, unsigned char *result){
    MD5_CTX md5_ctx;
    unsigned char buffer[1024];
    ssize_t bytes_read;

    MD5_Init(&md5_ctx);
    while ((bytes_read = read(fileDescriptor, buffer, sizeof(buffer))) > 0) {
        MD5_Update(&md5_ctx, buffer, bytes_read);
    }
    MD5_Final(result, &md5_ctx);

}



void printmd5(unsigned char *md){
    for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {
        printf("%02x", md[i]);
    }
    printf("\n");
}


// 将 unsigned char 数组转换为 char 字符串
void ucharToHexString(unsigned char *input, char *output, int length) {
    for (int i = 0; i < length; ++i) {
        sprintf(output + (i * 2), "%02x", input[i]);
    }
    output[length * 2] = '\0'; // 添加字符串结束符
}




/**
 * @brief 获得文件的逻辑大小
*/
long getFileSize(int fileDescriptor){
    struct stat st;
    memset(&st, 0, sizeof stat);
    fstat(fileDescriptor, &st);
    return st.st_size;
}


/**
 * @brief 获得空洞文件的已写入偏移量
*/
off_t getActualWrittenSize(const char *path) {
    int fd = open(path, O_RDONLY);

    struct stat st;
    fstat(fd, &st);

    unsigned char *file_data = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);

    off_t actual_size = 0;
    for (off_t i = 0; i < st.st_size; ++i) {
        if (file_data[i] != 0) {
            actual_size = i + 1;
        }
    }

    munmap(file_data, st.st_size);
    close(fd);
    return actual_size;
}

